var url = 'http://' + window.location.host + base_url + 'sockjs/echo';
var sockjsObj = null;
var transports = [];

function setConnected(connected) {
    document.getElementById('connect').disabled = connected;
    document.getElementById('disconnect').disabled = !connected;
    document.getElementById('username').disabled = connected;
    changeSendFormStatus(!connected)
    if (connected) {
        $("#loginPanel").hide()
        $("#userInfoPanel").show();
    } else {
        $("#userInfoPanel").hide();
        $("#loginPanel").show()
    }
}
/**
 * 发起连接
 */
function connect() {
    $("#username").blur();
    alertMsg(url, false);
    alertMsg(base_url, false);
    window.clearInterval(getOnlineInterval);
    var name = document.getElementById('username').value;
    if (!name || name.trim().length == 0) {
        alert('请输入昵称!')
        return;
    }
    if (name.length > 10) {
        alert('小样，昵称太长了!')
        return;
    }
    sockjsObj = new SockJS(url, undefined, transports);

    sockjsObj.onopen = function () {
        alertMsg('服务器连接成功!', false);
        setConnected(true);
        var username = document.getElementById('username').value;
        $("#nickName").text(username)
        sendMessage("login", username);
        getOnline();
    };
    sockjsObj.onmessage = function (event) {
        showMessage(JSON.parse(event.data));
    };
    sockjsObj.onclose = function (event) {
        setConnected(false);
        if (event.code == 1007) {
            alertMsg('小样，昵称太长了!', true);
        }
        alertMsg('断开连接!', true);
        setConnected(false);
    };
    $("#message").focus();
}
/**
 * 断开连接
 */
function disconnect() {
    if (sockjsObj != null) {
        sockjsObj.close();
        sockjsObj = null;
    }
    setConnected(false);
}
/**
 * 发送消息到服务器
 * @param cmd
 * @param message
 */
function sendMessage(cmd, message) {
    if (sockjsObj != null) {
        if (message.trim().length == 0) {
            alertMsg('请输入内容!', true)
            return;
        }
        if (message.length > 100) {
            alertMsg('太长了，明显是来刷屏的啊!', true);
            return;
        }
        var direct = $("#targetId").data("selectId");
        if(direct == undefined){
            direct = "";
        }
        if (direct != "" && cmd != "login") {
            //发送的是私密消息
            var directName = $("#targetId").data("selectName");
            showMessage({
                level: 0,
                msgCode: 2002,
                sourceId: "",
                sourceName: "你对" + directName + "说",
                directId: direct,
                directName: directName,
                msg: message,
                timeStr: new Date().Format("yyyy-MM-dd hh:mm:ss")
            })
        }
        changeSendFormStatus(true);
        var requestStr = JSON.stringify({cmd: cmd, msg: message, direct: direct});
        window.console.log("上行消息:" + requestStr);
        sockjsObj.send(requestStr);
        document.getElementById('messageText').value = '';
        changeSendFormStatus(false);
        $("#messageText").focus();
    } else {
        alert('connection not established, please connect.');
    }
};

function changeSendFormStatus(status) {
    document.getElementById('messageText').disabled = status;
    document.getElementById('messageBtn').disabled = status;
}
/**
 * 显示消息到聊天窗口
 * @param arg1
 */
function showMessage(messageObj) {
    window.console.log("下行消息:" + JSON.stringify(messageObj));
    if (messageObj.msgCode == 2000) {
        //登陆回复
        $("#loginPanel").data("sessionId", messageObj.msg);
        getOnlineInterval = window.setInterval(getOnline, 5000);
        return;
    } else if (messageObj.msgCode == 2003) {
        //登陆广播
        setTimeout(getOnline(), 200);
    }
    var msgText = messageObj.timeStr + "  [" + messageObj.sourceName + "] :" + messageObj.msg;
    var className = ""
    if (messageObj.level == 1) {
        className = "text-info"
    } else if (messageObj.level == 2) {
        className = "text-warning"
    } else if (messageObj.level == 3) {
        className = "text-danger"
    }
    if (messageObj.msgCode == 2002) {
        //私密消息
        className += " bg-success";
    }

    var messageConsole = document.getElementById('messageConsole');
    var p = document.createElement('p');
    p.style.wordWrap = 'break-word';
    p.className = className
    p.appendChild(document.createTextNode(msgText));
    messageConsole.appendChild(p);
    while (messageConsole.childNodes.length > 35) {
        messageConsole.removeChild(messageConsole.firstChild);
    }
    messageConsole.scrollTop = messageConsole.scrollHeight;
}

function alertMsg(msg, status) {
    window.console.log(msg);
    if (status) {

    }
}
var onlineTemplate = '<div class="media" id="$id" title="$name">' +
    '<div class="media-left">' +
    '<img class="media-object img-circle" data-src="holder.js/50x50" alt="50x50" data-holder-rendered="true" style="width: 50px; height: 50px;" src="static/img/head.jpg"/>' +
    '</div>' +
    '<div class="media-body">' +
    '<h4 class="media-heading">' +
    '$name' +
        //'<div class="badge">14</div>'+
    '</h4>' +
    '<p class="text-muted">...</p>' +
    '</div>' +
    '</div>';
/**
 * 获取在线用户
 */
function getOnline() {
    $.ajax({
        url: base_url + "chat/online",
        type: 'get',
        dataType: "json",
        success: function (data, status) {
            $("#onlineUserList .media").not(".square").remove();
            if (data != null && data != undefined && data.length > 0) {
                //将自己移除
                var myId = $("#loginPanel").data("sessionId");
                for (i = 0; i < data.length; i++) {
                    if (data[i].id == myId) {
                        continue;
                    }
                    var template = onlineTemplate.concat();
                    template = template.replace(new RegExp('\\$name', 'g'), data[i].name).replace(new RegExp('\\$id', 'g'), data[i].id);
                    $("#onlineUserList").append(template)
                }
                bindOnlineEvent();
            }
        },
        error: function (data, status, e) {
        }
    });
}
/**
 * 绑定在线用户事件
 */
function bindOnlineEvent() {
    $("#onlineUserList .media").on("mouseover", function () {
        $(this).addClass("bg-info");
        $(this).css({cursor: "pointer"});
    }).on("mouseout", function () {
        $(this).removeClass("bg-info");
        $(this).css({cursor: "none"});
    }).on("click", function () {
        var _id = $(this).attr("id");
        var _name = $(this).attr("title");
        $("#targetId").val(_id);
        $("#targetId").data("selectId", _id);
        $("#targetId").data("selectName", _name);
        $("#targetNameTop").text("[" + _name + "]");
        if ($(this).attr("id") == "") {
            $("#messageText").attr("placeholder", "发布信息到广场...");
        } else {
            $("#messageText").attr("placeholder", "私密给" + _name + "...");
        }
    })
}


Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
